<template>
  <el-menu :default-active="activeMenu" mode="horizontal" @select="handleSelect" :ellipsis="false">
    <template v-for="(item, index) in topMenus">
      <el-menu-item :style="{ '--theme': theme }" :index="item.path" :key="index" v-if="index < visibleNumber">
        <span class="icon-box" :style="{ background: colorList[index] }">
          <svg-icon v-if="item.meta && item.meta.icon && item.meta.icon !== '#'" :icon-class="item.meta.icon" />
        </span>
        {{ item.meta.title }}
      </el-menu-item>
    </template>

    <!-- 顶部菜单超出数量折叠 -->
    <el-sub-menu :style="{ '--theme': theme }" index="more" v-if="topMenus.length > visibleNumber">
      <template #title>更多菜单</template>
      <template v-for="(item, index) in topMenus">
        <el-menu-item :index="item.path" :key="index" v-if="index >= visibleNumber">
          <svg-icon v-if="item.meta && item.meta.icon && item.meta.icon !== '#'" :icon-class="item.meta.icon" />
          {{ item.meta.title }}
        </el-menu-item>
      </template>
    </el-sub-menu>
  </el-menu>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { constantRoutes } from '@/router'
import { isHttp } from '@/utils/validate'
import useAppStore from '@/store/modules/app'
import useSettingsStore from '@/store/modules/settings'
import usePermissionStore from '@/store/modules/permission'

// 顶部栏初始数
const visibleNumber = ref(null)
// 当前激活菜单的 index
const currentIndex = ref(null)
// 隐藏侧边栏路由
const hideList = ['/index', '/user/profile']

const appStore = useAppStore()
const settingsStore = useSettingsStore()
const permissionStore = usePermissionStore()
const route = useRoute()
const router = useRouter()

const colorList = ref([
  'rgb(120, 200, 99)',
  'rgb(255, 140, 102)',
  'rgb(65, 214, 150)',
  'rgb(49, 169, 239)',
  '#FF69B4',
  '#BA55D3',
  '#40E0D0',
  '#1E90FF',
  '#FFD700',
  '#00FA9A',
])
// 主题颜色
const theme = computed(() => settingsStore.theme)
// 所有的路由信息
const routers = computed(() => permissionStore.topbarRouters)

// 顶部显示菜单
const topMenus = computed(() => {
  let topMenus = []
  routers.value.map(menu => {
    if (menu.hidden !== true) {
      // 兼容顶部栏一级菜单内部跳转
      if (menu.path === '/' && menu.children) {
        topMenus.push(menu.children[0])
      } else {
        topMenus.push(menu)
      }
    }
  })
  return topMenus
})

// 递归扁平化路由 - 保留所有层级
function flattenRoutes(routes, parentPath = '') {
  const result = []

  routes.forEach(route => {
    // 创建路由副本
    const routeItem = { ...route }

    // 设置完整路径
    if (parentPath === '/' || !parentPath) {
      routeItem.path = route.path.startsWith('/') ? route.path : '/' + route.path
    } else {
      if (!isHttp(route.path) && !route.path.startsWith('/')) {
        routeItem.path = parentPath + '/' + route.path
      } else {
        routeItem.path = route.path
      }
    }

    // 设置父路径
    routeItem.parentPath = parentPath || '/'

    // 添加当前路由到结果
    result.push(routeItem)

    // 递归处理子路由
    if (route.children && route.children.length > 0) {
      const children = flattenRoutes(route.children, routeItem.path)
      result.push(...children)
    }
  })

  return result
}

// 查找第一个叶子节点（用于自动跳转）
function findFirstLeafRoute(routes, parentPath = '') {
  if (!routes || routes.length === 0) return null

  for (const route of routes) {
    if (route.hidden) continue

    // 构建当前路由的完整路径
    let currentPath = route.path
    if (parentPath) {
      if (parentPath === '/' || parentPath === '') {
        currentPath = currentPath.startsWith('/') ? currentPath : '/' + currentPath
      } else {
        if (!currentPath.startsWith('/') && !isHttp(currentPath)) {
          currentPath = parentPath + '/' + currentPath
        }
      }
    }

    // 如果没有子路由或子路由为空，这是叶子节点
    if (!route.children || route.children.length === 0) {
      return { ...route, fullPath: currentPath }
    } else {
      // 继续递归查找
      const leafRoute = findFirstLeafRoute(route.children, currentPath)
      if (leafRoute) return leafRoute
    }
  }

  return null
}

// 设置子路由
const childrenMenus = computed(() => {
  const allChildren = []
  routers.value.forEach(router => {
    if (router.children && router.children.length > 0) {
      const flattened = flattenRoutes(router.children, router.path)

      allChildren.push(...flattened)
    }
  })

  const result = constantRoutes.concat(allChildren)
  return result
})

// 默认激活的菜单
const activeMenu = computed(() => {
  const path = route.path
  let activePath = path

  // 检查是否为隐藏路由（如字典数据详情页等）
  const isHiddenRoute =
    path.includes('/system/message') ||
    path.includes('/system/dict-data/') ||
    path.includes('/system/user-auth/') ||
    path.includes('/system/role-auth/') ||
    path.includes('/monitor/job-log/') ||
    path.includes('/tool/gen-edit/')

  if (isHiddenRoute) {
    // 对于隐藏路由，不进行自动跳转，直接返回对应的顶级菜单路径
    if (path.startsWith('/system/message')) {
      return '/system'
    } else if (path.startsWith('/system/dict-data/')) {
      return '/system'
    } else if (path.startsWith('/monitor/job-log/')) {
      return '/monitor'
    } else if (path.startsWith('/tool/gen-edit/')) {
      return '/tool'
    }
    // 其他隐藏路由保持原逻辑
    if (path !== undefined && path.lastIndexOf('/') > 0 && hideList.indexOf(path) === -1) {
      const tmpPath = path.substring(1, path.length)
      if (!route.meta?.link) {
        activePath = '/' + tmpPath.substring(0, tmpPath.indexOf('/'))
        appStore.toggleSideBarHide(false)
      }
    }
    return activePath
  }

  if (path !== undefined && path.lastIndexOf('/') > 0 && hideList.indexOf(path) === -1) {
    const tmpPath = path.substring(1, path.length)
    if (!route.meta?.link) {
      activePath = '/' + tmpPath.substring(0, tmpPath.indexOf('/'))
      appStore.toggleSideBarHide(false)
    }
  } else if (!route.children) {
    activePath = path
    appStore.toggleSideBarHide(true)
  }

  const routes = activeRoutes(activePath)

  // 如果当前路径不在子菜单中，且有子菜单，则跳转到第一个叶子节点
  if (routes && routes.length > 0 && !appStore.sidebar.hide) {
    // 检查当前路径是否存在于扁平化的路由中
    const currentRouteExists = childrenMenus.value.some(item => item.path === path)

    if (!currentRouteExists) {
      // 找到对应的顶级路由
      const topRoute = routers.value.find(item => item.path === activePath)

      if (topRoute && topRoute.children) {
        // 从原始路由结构中找到第一个叶子节点
        const leafRoute = findFirstLeafRoute(topRoute.children, activePath)

        if (leafRoute && leafRoute.fullPath) {
          // 在扁平化的路由中找到对应的完整路径
          const targetRoute = childrenMenus.value.find(item => item.path === leafRoute.fullPath)

          if (targetRoute && path !== targetRoute.path) {
            // 使用 nextTick 确保在下次 DOM 更新后执行路由跳转
            nextTick(() => {
              if (targetRoute.query) {
                const query = JSON.parse(targetRoute.query)
                router.push({ path: targetRoute.path, query: query })
              } else {
                router.push({ path: targetRoute.path })
              }
            })
          }
        }
      }
    }
  }
  return activePath
})

function setVisibleNumber() {
  const width = document.body.getBoundingClientRect().width / 3
  visibleNumber.value = parseInt(width / 85)
}

function handleSelect(key, keyPath) {
  currentIndex.value = key
  const topRoute = routers.value.find(item => item.path === key)
  if (isHttp(key)) {
    // http(s):// 路径新窗口打开
    window.open(key, '_blank')
  } else if (!topRoute || !topRoute.children || topRoute.children.length === 0) {
    // 没有子路由路径内部打开
    const keyCopy = key[0] === '/' ? key : '/' + key
    const routeMenu = childrenMenus.value.find(item => item.path === keyCopy)

    if (routeMenu && routeMenu.query) {
      let query = JSON.parse(routeMenu.query)
      router.push({ path: keyCopy, query: query })
    } else {
      router.push({ path: keyCopy })
    }
    appStore.toggleSideBarHide(true)
  } else {
    // 显示左侧联动菜单（完整层级结构）
    const routes = activeRoutes(key)
    appStore.toggleSideBarHide(false)

    // 自动跳转到第一个叶子节点
    if (routes && routes.length > 0) {
      // 从原始路由结构中找到第一个叶子节点，传入顶级路径
      const leafRoute = findFirstLeafRoute(topRoute.children, key)

      if (leafRoute && leafRoute.fullPath) {
        // 在扁平化的路由中找到对应的完整路径
        const targetRoute = childrenMenus.value.find(item => item.path === leafRoute.fullPath)

        if (targetRoute) {
          if (targetRoute.query) {
            const query = JSON.parse(targetRoute.query)
            router.push({ path: targetRoute.path, query: query })
          } else {
            router.push({ path: targetRoute.path })
          }
        }
      }
    }
  }
}

function activeRoutes(key) {
  let routes = []

  // 直接从原始路由结构中获取对应顶级菜单的子路由
  const topRoute = routers.value.find(item => item.path === key)

  if (topRoute && topRoute.children && topRoute.children.length > 0) {
    // 处理子路由，确保路径正确
    const processRoutes = (routes, parentPath = '') => {
      return routes.map(route => {
        const processedRoute = { ...route }

        // 构建完整路径
        if (route.path && route.path.startsWith('/')) {
          // 如果已经是绝对路径，直接使用
          processedRoute.path = route.path
        } else {
          // 拼接父路径
          if (parentPath === '/' || !parentPath) {
            processedRoute.path = '/' + (route.path || '')
          } else {
            processedRoute.path = parentPath + '/' + (route.path || '')
          }
        }

        // 递归处理子路由
        if (route.children && route.children.length > 0) {
          processedRoute.children = processRoutes(route.children, processedRoute.path)
        }

        return processedRoute
      })
    }

    routes = processRoutes(topRoute.children, key)
    permissionStore.setSidebarRouters(routes)
    return routes
  } else {
    appStore.toggleSideBarHide(true)
    return []
  }
}

onMounted(() => {
  window.addEventListener('resize', setVisibleNumber)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', setVisibleNumber)
})

onMounted(() => {
  setVisibleNumber()
})
</script>

<style lang="scss">
.el-menu--horizontal > .el-sub-menu .el-sub-menu__title {
  color: #fff !important;
}
.el-menu--horizontal > .el-sub-menu .el-sub-menu__title:hover {
  background-color: #2460c2;
}
.el-menu--popup-bottom-start {
  background-color: #2460c2 !important;
  .el-menu-item {
    background-color: #2460c2 !important;
    color: #fff !important;
  }
}
</style>
<style lang="scss" scoped>
.el-menu {
  // padding: 15px 0;
  display: flex;
  align-items: center;
  background: transparent;
}
.topmenu-container.el-menu--horizontal > .el-menu-item {
  float: left;
  height: 100% !important;
  line-height: 50px !important;
  color: #fff !important;
  padding: 0 15px !important;
  margin: 0 10px !important;
  border-radius: 6px;
}
.topmenu-container.el-menu--horizontal > .el-menu-item.is-active,
.el-menu--horizontal > .el-sub-menu.is-active .el-submenu__title {
  border-bottom: none !important;
  color: #fff !important;
  background: #2460c2 !important;
  padding: 0 15px !important;
}

/* sub-menu item */
.topmenu-container.el-menu--horizontal > .el-sub-menu .el-sub-menu__title {
  float: left;
  height: 50px !important;
  line-height: 50px !important;
  color: #fff !important;
  padding: 0 5px !important;
  margin: 0 10px !important;
}

.el-menu--horizontal.el-menu {
  border: none;
}

/* 背景色隐藏 */
.topmenu-container.el-menu--horizontal > .el-menu-item:not(.is-disabled):focus,
.topmenu-container.el-menu--horizontal > .el-menu-item:not(.is-disabled):hover,
.topmenu-container.el-menu--horizontal > .el-submenu .el-submenu__title:hover {
  background-color: #2460c2;
}

.icon-box {
  width: 26px;
  height: 26px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  border-radius: 13px;
  margin-right: 5px;
}

/* topmenu more arrow */
.topmenu-container .el-sub-menu .el-sub-menu__icon-arrow {
  position: static;
  vertical-align: middle;
  margin-left: 8px;
  margin-top: 0px;
}
</style>
